#include	"Wiimote4Virtools.h"
#include	"WiimMotions.h"

CKObjectDeclaration *FillBehaviorWiimMotions()
{
	CKObjectDeclaration *od = CreateCKObjectDeclaration ( "WiimMotions" );
	od->SetDescription ( "Gets motion data from a Wiimote." );
	od->SetCategory ( "Wiimote" );
	od->SetType ( CKDLL_BEHAVIORPROTOTYPE );
	od->SetGuid ( WIIMMOTIONS_GUID );
	od->SetAuthorGuid ( AUTHOR_GUID );
	od->SetAuthorName ( "Jonathan DERROUGH" );
	od->SetVersion ( 0x00000001 );
	od->SetCreationFunction ( CreateWiimMotionsProto );
	//od->SetCompatibleClassId ( CKCID_3DENTITY );
	return od;
}

CKERROR CreateWiimMotionsProto ( CKBehaviorPrototype **pproto)
{
	CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("WiimMotions");

	if(!proto)
		return (CKERR_OUTOFMEMORY);

	proto->DeclareInput("In");
	proto->DeclareOutput("Out");

	proto->DeclareInParameter("Wiimote id", CKPGUID_INT );
	proto->DeclareOutParameter("Motion", CKPGUID_VECTOR );

	//TODO : Add support to Wiim for other motions

	proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL);
	proto->SetFunction(WiimMotions);
	//proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE);

	*pproto = proto;
	return (CK_OK);
}

int WiimMotions(const CKBehaviorContext& behcontext)
{
	CKBehavior* beh = behcontext.Behavior;

	beh->ActivateInput(0, FALSE);	// deactivation

	// Wiimote(s) present ?
	if (g_wiimotes.size() < 1)
	{
		beh->ActivateOutput(1);
		return (CKBR_OK);
	}

	// Get the id of the Wiimote we are using
	int wiimote_id = 0;
	beh->GetInputParameterValue(0, &wiimote_id);

	if (wiimote_id >= g_wiimotes.size())
	{
		beh->ActivateOutput(0);
		return (CKBR_PARAMETERERROR);
	}

	MotionData p = g_wiimotes[wiimote_id].GetLastMotionData();
	VxVector v;
	v.Set(-p.x, -p.y, -p.z);

	beh->SetOutputParameterValue(0, &v);
	
	beh->ActivateOutput(0);
	return (CKBR_OK);
}